<template>
	<div class="container-fluid">
		<div class="panel">
			<div class="panel-heading">
				<el-row class="heading-row">
					<el-col :span="2">
						<div class="grid-content bg-purple">
							<el-button type="primary" plain @click="createShop" icon="el-icon-plus">人员</el-button>
						</div>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<collapse-view content="高级搜索">
							<el-form :model="queryParams" label-width="40px" label-position="right" :inline="true" ref="searchForm">
								<el-form-item label="姓名">
									<el-input v-model="queryParams.name" placeholder="输入姓名" clearable></el-input>
								</el-form-item>
								<el-form-item label="账号">
									<el-input v-model="queryParams.staffid" placeholder="输入账号" clearable></el-input>
								</el-form-item>
								<el-form-item>
									<el-button @click="fetchUsers">搜索</el-button>
									<el-button @click="clearSearchForm">清除</el-button>
								</el-form-item>
							</el-form>
						</collapse-view>
					</el-col>
				</el-row>
				<el-dialog title="添加人员信息" :visible.sync="create" width="30%" :before-close="handleCreateClose">
					<el-form ref="createUser" :model="createParams" label-width="50px" label-position="right" :rules="createRules">
						<el-form-item label="姓名" prop="name">
							<el-input v-model="createParams.name" auto-complete="off" placeholder="请输人员姓名"></el-input>
						</el-form-item>
						<el-form-item label="账号" prop="staffid">
							<el-input v-model="createParams.staffid" auto-complete="off" placeholder="请输人员账号"></el-input>
						</el-form-item>
						<el-form-item label="密码" prop="password">
							<el-input type="password" v-model="createParams.password" auto-complete="off" placeholder="请输人员密码"></el-input>
						</el-form-item>
						<el-form-item label="电话" prop="phone">
							<el-input v-model="createParams.phone" auto-complete="off" placeholder="请输入联系电话"></el-input>
						</el-form-item>
						<el-form-item label="邮箱">
							<el-input v-model="createParams.email" auto-complete="off" placeholder="请输入邮箱地址"></el-input>
						</el-form-item>
						<el-form-item label="备注">
							<el-input v-model="createParams.remarks" auto-complete="off" placeholder="请输入备注"></el-input>
						</el-form-item>
						<el-form-item label="角色" v-if="createParams.admin">
							<el-select v-model="createParams.role" placeholder="请选择角色">
								<el-option v-for="item in roles" :key="item.code" :label="item.name" :value="item.code"></el-option>
							</el-select>
						</el-form-item>
						<el-row>
							<el-col :span="12">
								<el-form-item label="是否是管理员" label-width="120px">
									<el-switch v-model="createParams.admin" active-color="#13ce66" :inactive-value="0" :active-value="1"></el-switch>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="性别">
									<el-radio-group v-model="createParams.gender">
										<el-radio label="male">男士</el-radio>
										<el-radio label="female">女士</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button @click="create = false">取 消</el-button>
						<el-button type="primary" @click="submitCreateForm">确 定</el-button>
					</div>
				</el-dialog>
				<!-- 编辑人员信息 -->
				<el-dialog title="编辑人员信息" :visible.sync="edit" width="30%" :before-close="handleEditClose">
					<el-form ref="editUser" :model="editParams" label-width="50px" label-position="right" :rules="editRules">
						<el-form-item label="姓名" prop="name">
							<el-input v-model="editParams.name" auto-complete="off" placeholder="请输入人员姓名"></el-input>
						</el-form-item>
						<el-form-item label="账号" prop="staffid">
							<el-input v-model="editParams.staffid" auto-complete="off" placeholder="请输入人员账号"></el-input>
						</el-form-item>
						<el-form-item label="电话" prop="phone">
							<el-input v-model="editParams.phone" auto-complete="off" placeholder="请输入联系电话"></el-input>
						</el-form-item>
						<el-form-item label="邮箱">
							<el-input v-model="editParams.email" auto-complete="off" placeholder="请输入邮箱"></el-input>
						</el-form-item>
						<el-form-item label="备注">
							<el-input v-model="editParams.remarks" auto-complete="off" placeholder="请输入备注"></el-input>
						</el-form-item>
						<el-form-item label="角色" v-if="editParams.admin">
							<el-select v-model="editParams.roles" placeholder="请选择角色" multiple>
								<el-option v-for="item in roles" :key="item.code" :label="item.name" :value="item.code"></el-option>
							</el-select>
						</el-form-item>
						<el-row>
							<el-col :span="12">
								<el-form-item label="是否是管理员" label-width="120px">
									<el-switch v-model="editParams.admin" active-color="#13ce66" :inactive-value="0" :active-value="1"></el-switch>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="性别">
									<el-radio-group v-model="editParams.gender">
										<el-radio label="male">男士</el-radio>
										<el-radio label="female">女士</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button @click="edit = false">取 消</el-button>
						<el-button type="primary" @click="submitEditForm">确 定</el-button>
					</div>
				</el-dialog>
			</div>

			<div class="panel-body">
				<el-table :data="users.data" style="width: 100%" v-loading="loading">
					<el-table-column label="账号" prop="staffid"></el-table-column>
					<el-table-column label="姓名" prop="name"></el-table-column>
					<el-table-column label="电话" prop="phone"></el-table-column>
					<el-table-column label="邮箱" prop="email"></el-table-column>
					<el-table-column label="备注" prop="remarks"></el-table-column>
					<el-table-column label="管理员">
						<template slot-scope="scope">
							<el-tag size="mini" :type="scope.row.admin ? '' : 'info'">{{ scope.row.admin ? '是' : '否' }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作">
						<template slot-scope="scope">
							<el-button size="mini" icon="el-icon-edit-outline" @click="handleEdit(scope.$index, scope.row)"></el-button>
							<el-button size="mini" type="danger" icon="el-icon-close" @click="handleDelete(scope.$index, scope.row)" plain></el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="panel-footer text-right">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
											 :current-page="queryParams.page"
											 :page-sizes="[10, 20, 50, 100]"
											 :page-size="queryParams.paginate"
											 layout="total, sizes, prev, pager, next, jumper"
											 :total="users.total">
				</el-pagination>
			</div>
		</div>
	</div>
</template>

<script>
	import Vue from 'vue'
	import api from '../apis'

	export default {
		name: "user",
		data () {
			/**
			 * 自定义验证
			 */
			var validatePhone = (rule, value, callback) => {
		        if (value === '') {
		        	callback();
		        } else {
		        	var reg = /^1[0-9]{10}$/;
		        	if(!reg.test(value)){
		          		callback(new Error('联系电话格式错误'));
		        	}else{
		        		callback();
		        	}
		        }
		    };
			return {
				loading: false,
				create: false,
				edit: false,
				search: '',
				searchOption: '',

				createParams: {
					name: '',
					staffid: '',
					roles: [],
					gender: 'male',
					email: '',
					password: '',
					admin: '',
					remarks: '',
					phone: ''
				},
				editParams: {
					name: '',
					staffid: '',
					roles: [],
					gender: 'male',
					email: '',
					admin: '',
					remarks: '',
					phone: ''
				},
				createRules: {
					name: [
						{ required: true, message: '请输入用户姓名', trigger: 'blur' }
					],
					staffid: [
						{ required: true, message: '请输入用户账号', trigger: 'blur' }
					],
					password: [
						{ required: true, message: '请输入用户密码', trigger: 'blur' }
					],
					phone: [
						{ required: false, validator: validatePhone, trigger: 'blur' }
					]
				},
				editRules: {
					name: [
						{ required: true, message: '请输入用户姓名', trigger: 'blur' }
					],
					staffid: [
						{ required: true, message: '请输入用户账号', trigger: 'blur' }
					],
					phone: [
						{ required: false, validator: validatePhone, trigger: 'blur' }
					]
				},
				roles: [],
				users: {
					data: [],
					total: 0
				},
				queryParams: {
					page: 1,
					paginate: 10,
					name: '',
					staffid: '',
				}
			}
		},
		methods: {
			fetchUsers () {
				this.loading = true;
				api.user.fetch(this.queryParams).then(response => {
					this.users = response.data;
					this.loading = false;
				})
			},
			fetchRoles () {
				api.role.fetchRoles().then(response => {
					this.roles = response.data;
				});
			},
			fetchUser (id) {
				api.user.fetchByID(id, {
					role: 1
				}).then(response => {
					this.editParams.roles = response.data;
				});
			},
			handleEdit (index, row) {
				this.edit = true;
				this.editParams = {...row};
				this.fetchUser(row.id);
				this.editParams.index = index;
			},
			/**
			 * 删除用户信息
			 */
			handleDelete (index, row) {
				this.$confirm('此操作将删除用户信息, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					api.user.destroy(row.id).then(() => {
						Vue.delete(this.users.data, index);
						this.users.total -= 1;
						this.$message.success('删除成功');
					}).catch(errors => {
						this.$message.error(errors.response.data.error);
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			/**
			 * 当改变分页大小时重新获取用户数据
			 */
			handleSizeChange (size) {
				this.queryParams.paginate = size;
				this.fetchUsers();
			},
			/**
			 * 当改变页码时重新获用户数据
			 */
			handleCurrentChange (index) {
				this.queryParams.page = index;
				this.fetchUsers();
			},
			/**
			 * 创建用户信息
			 */
			createShop () {
				this.create = true;
			},
			/**
			 * 提交创建用户信息表单
			 */
			submitCreateForm () {
				this.$refs['createUser'].validate((valid) => {
					if (valid) {
						api.user.store(this.createParams).then(response => {
							this.users.data.push(response.data);
							this.handleCreateClose();
							this.users.total += 1;
							this.jumpToLastPage();
							this.$message.success('分类创建成功');
						}).catch(errors => {
							this.$message.error(errors.response.data.error);
						});
					} else {
						return false;
					}
				});
			},
			submitEditForm () {
				this.$refs['editUser'].validate((valid) => {
					if(valid){
						api.user.update(this.editParams.id, this.editParams).then(response => {
							Vue.set(this.users.data, this.editParams.index, response.data);
							this.$message.success('更新成功');
							this.handleEditClose();
						}).catch(errors => {
							this.$message.error(errors.response.data.error);
						})
					}else{
						return false;
					}
				});
			},
			/**
			 * 跳转到最后一页
			 */
			jumpToLastPage () {
				let last = Math.ceil(this.users.total / this.queryParams.paginate);
				if (this.queryParams.page < last) {
					this.queryParams.page = last;
				}
			},
			/**
			 * 关闭表单
			 */
			handleCreateClose () {
				this.create = false;
				this.createParams.email = '';
				this.$refs['createUser'].resetFields();
			},
			handleEditClose () {
				this.edit = false;
				this.editParams = {
					name: '',
					staffid: '',
					roles: [],
					gender: 'male',
					email: '',
					admin: ''
				};
				this.$refs['editUser'].resetFields();
			},
			/**
			 * 清空搜索表单
			 */
			clearSearchForm () {
				this.queryParams.name = '';
				this.queryParams.staffid = '';
			}
		},
		mounted () {
			this.fetchUsers();
			this.fetchRoles();
		}
	}
</script>

<style lang="scss">
	.el-select--small {
		width: 100%;
	}
</style>
